package org.apache.mina.example.http;

import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.util.HashMap;
import java.util.Map;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.http.DecoderState;
import org.apache.mina.http.HttpRequestImpl;
import org.apache.mina.http.api.HttpMethod;
import org.apache.mina.http.api.HttpRequest;
import org.apache.mina.http.api.HttpVersion;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HttpHandler extends IoHandlerAdapter{
	   private static final Logger LOGGER = LoggerFactory.getLogger(HttpHandler.class);

	    public void sessionCreated(IoSession session) throws Exception {
	        // Empty handler
	    	LOGGER.info("session create");
	    }

	    public void sessionOpened(IoSession session) throws Exception {
	    	HttpVersion version=HttpVersion.HTTP_1_1;
	    	HttpMethod method =HttpMethod.GET;
	    	String requestedPath = "/";
	    	String queryString = "";
	    	Map<String ,String > headers= new HashMap<String, String>();
	    	HttpRequest request = new HttpRequestImpl(version, method, requestedPath, queryString, headers);
	    	session.write(request);
	    	LOGGER.info("session open");
	    }

	    public void sessionClosed(IoSession session) throws Exception {
	    	LOGGER.info("session closed");
	    	session.close(false);
	        // Empty handler
	    }

	    public void sessionIdle(IoSession session, IdleStatus status) throws Exception {
	    	LOGGER.info("session idle");
	        // Empty handler
	    }

	    public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
	        if (LOGGER.isWarnEnabled()) {
	            LOGGER.warn("EXCEPTION, please implement " + getClass().getName()
	                    + ".exceptionCaught() for proper handling:", cause);
	        }
	    }

	    public void messageReceived(IoSession session, Object message) throws Exception {
	    	if(message instanceof IoBuffer){
	    	    LOGGER.info(((IoBuffer)message).getString(Charset.forName("utf-8").newDecoder()));
	    	}
	    	LOGGER.info("session receviced"+message);
	    	
	    	
	    }

	    public void messageSent(IoSession session, Object message) throws Exception {
	    	LOGGER.info("session sent"+message);
	    }
}
